import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import Md5 from 'js-md5'

/**
 * 计算一个请求的VC值
 * @param request http请求
 * @returns {String} VC值
 */
const vc = data => {
  let strTemp = ''
  if (!isNil2(data)) {
    const requestKeys = []
    for (const key in data) {
      requestKeys.push(key)
    }

    requestKeys.sort()

    for (let i = 0; i < requestKeys.length; i++) {
      strTemp += data[requestKeys[i]] + '#'
    }
  }
  strTemp += 'CSZHC#^%'
  return Md5(strTemp).toString()
}

const isNil2 = o => {
  return (o === null && typeof o === 'object') || o === undefined
}

export const hasChild = item => {
  return item.children && item.children.length !== 0
}

const service = axios.create({
  baseURL: 'http://api.market.cailanzi001.com', // url = base url + request url
  timeout: 500000 // request timeout
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = getToken()
      config.headers.Accept = 'application/json'
      config.headers.VC = vc(config.data)
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
      /* Message({
        message: '暂无数据',
        type: 'error',
        duration: 5 * 1000
      })*/
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          removeToken()
          location.reload()
          Message({
            message: '未登录，或登录失效，请登录',
            type: 'error'
          })
          break
      }
    }
    console.log('err' + error)
    // Message({
    //   message: '暂无数据',
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
